<?php

class App_Session_SaveHandler implements Zend_Session_SaveHandler_Interface
{

	/**
	 *
	 * @var string 
	 */
	private $_save_path;

	/**
	 *
	 * @var string
	 */
	private $_name;

	public function open($save_path, $name)
	{
		$this->_save_path = $save_path;
		$this->_name = $name;

		if (!is_writable($this->_save_path))
		{
			throw new App_Session_SaveHandler_Exception('Session save path is not writable');
		}

		return true;
	}

	public function close()
	{
		return true;
	}

	public function read($id)
	{
		$filename = $this->_save_path . '/' . $id . '.sess';

		$return = '';
		if (is_file($filename))
		{
			$return = (string) @file_get_contents($filename);
		}

		return $return;
	}

	public function write($id, $data)
	{
		$filename = $this->_save_path . '/' . $id . '.sess';
		@file_put_contents($filename, $data);

		return true;
	}

	public function destroy($id)
	{
		$filename = $this->_save_path . '/' . $id . '.sess';
		return (boolean) @unlink($filename);
	}

	public function gc($maxlifetime)
	{
		foreach (glob($this->_save_path . DIRECTORY_SEPARATOR . '*.sess') as $filename)
		{
			if (filemtime($filename) + $maxlifetime < time())
			{
				@unlink($filename);
			}
		}

		return true;
	}

}